import React, { useState } from 'react';
import { UserIcon, LockClosedIcon, AcademicCapIcon, ShieldCheckIcon } from '@heroicons/react/24/outline';
import { LoginForm, UserRole } from '../shared/types';

type Props = {
  onLogin?: (user: any) => void;
}

const Login = ({ onLogin }: Props) => {
  const [formData, setFormData] = useState({
    username: '',
    password: '',
    userType: 'student',
    captcha: ''
  });
  const [errors, setErrors] = useState({});
  const [isLoading, setIsLoading] = useState(false);
  const [loginAttempts, setLoginAttempts] = useState(0);
  const [captchaCode, setCaptchaCode] = useState('');
  const [showCaptcha, setShowCaptcha] = useState(false);

  // 生成随机验证码
  const generateCaptcha = () => {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < 4; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    setCaptchaCode(result);
    return result;
  };

  // 初始化验证码
  React.useEffect(() => {
    if (showCaptcha) {
      generateCaptcha();
    }
  }, [showCaptcha]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setErrors({});

    try {
      // 如果显示验证码，先验证验证码
      if (showCaptcha) {
        if (formData.captcha.toLowerCase() !== captchaCode.toLowerCase()) {
          setErrors({ captcha: '验证码错误，请重新输入' });
          generateCaptcha(); // 重新生成验证码
          setIsLoading(false);
          return;
        }
      }

      // 这里应该调用实际的登录API
      console.log('登录数据:', formData);
      
      // 模拟登录失败（用于测试验证码功能）
      if (formData.username === 'test' && formData.password === 'test') {
        // 模拟登录成功
        const mockUser = {
          id: '1',
          username: formData.username,
          role: formData.userType === 'admin' ? UserRole.ADMIN : UserRole.STUDENT,
          name: formData.userType === 'admin' ? '张管理员' : '李学生'
        };
        
        if (onLogin) {
          onLogin(mockUser);
        }
        
        alert('登录成功！');
        // 重置登录尝试次数
        setLoginAttempts(0);
        setShowCaptcha(false);
      } else {
        // 模拟登录失败
        const newAttempts = loginAttempts + 1;
        setLoginAttempts(newAttempts);
        
        if (newAttempts >= 2) {
          setShowCaptcha(true);
          setErrors({ general: '登录失败，请检查工号/学号和密码，并输入验证码' });
        } else {
          setErrors({ general: '登录失败，请检查工号/学号和密码' });
        }
      }
    } catch (error) {
      setErrors({ general: '登录失败，请检查工号/学号和密码' });
    } finally {
      setIsLoading(false);
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
    // 清除对应字段的错误
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: '' }));
    }
  };

  const handleRefreshCaptcha = () => {
    generateCaptcha();
  };

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col justify-center py-12 sm:px-6 lg:px-8">
      <div className="sm:mx-auto sm:w-full sm:max-w-md">
        <div className="flex justify-center">
          <div className="w-20 h-20 bg-primary rounded-full flex items-center justify-center">
            <UserIcon className="w-10 h-10 text-white" />
          </div>
        </div>
        <h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
          海大体育馆管理系统
        </h2>
        <p className="mt-2 text-center text-sm text-gray-600">
          请登录您的账户
        </p>
      </div>

      <div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
        <div className="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10">
          <form className="space-y-6" onSubmit={handleSubmit}>
            {/* 用户类型选择 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-3">
                登录身份
              </label>
              <div className="grid grid-cols-2 gap-3">
                <button
                  type="button"
                  className={`${
                    formData.userType === 'student'
                      ? 'bg-primary text-white border-primary'
                      : 'bg-white text-gray-700 border-gray-300'
                  } border-2 rounded-lg p-3 flex items-center justify-center space-x-2 transition-colors hover:bg-primary-100`}
                  onClick={() => setFormData(prev => ({ ...prev, userType: 'student' }))}
                >
                  <AcademicCapIcon className="w-5 h-5" />
                  <span>学生</span>
                </button>
                <button
                  type="button"
                  className={`${
                    formData.userType === 'admin'
                      ? 'bg-primary text-white border-primary'
                      : 'bg-white text-gray-700 border-gray-300'
                  } border-2 rounded-lg p-3 flex items-center justify-center space-x-2 transition-colors hover:bg-primary-100`}
                  onClick={() => setFormData(prev => ({ ...prev, userType: 'admin' }))}
                >
                  <ShieldCheckIcon className="w-5 h-5" />
                  <span>管理员</span>
                </button>
              </div>
            </div>

            {/* 工号/学号 */}
            <div>
              <label htmlFor="username" className="block text-sm font-medium text-gray-700">
                {formData.userType === 'student' ? '学号' : '工号'}
              </label>
              <div className="mt-1 relative">
                <input
                  id="username"
                  name="username"
                  type="text"
                  required
                  value={formData.username}
                  onChange={handleInputChange}
                  className="appearance-none block w-full px-3 py-2 pl-10 border border-gray-300 rounded-md placeholder-gray-400 focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"
                  placeholder={formData.userType === 'student' ? '请输入学号' : '请输入工号'}
                />
                <UserIcon className="w-5 h-5 text-gray-400 absolute left-3 top-2.5" />
              </div>
              {errors.username && (
                <p className="mt-1 text-sm text-red-600">{errors.username}</p>
              )}
            </div>

            {/* 密码 */}
            <div>
              <label htmlFor="password" className="block text-sm font-medium text-gray-700">
                密码
              </label>
              <div className="mt-1 relative">
                <input
                  id="password"
                  name="password"
                  type="password"
                  required
                  value={formData.password}
                  onChange={handleInputChange}
                  className="appearance-none block w-full px-3 py-2 pl-10 border border-gray-300 rounded-md placeholder-gray-400 focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"
                  placeholder="请输入密码"
                />
                <LockClosedIcon className="w-5 h-5 text-gray-400 absolute left-3 top-2.5" />
              </div>
              {errors.password && (
                <p className="mt-1 text-sm text-red-600">{errors.password}</p>
              )}
            </div>

            {/* 图形验证码 */}
            {showCaptcha && (
              <div>
                <label htmlFor="captcha" className="block text-sm font-medium text-gray-700">
                  图形验证码 *
                </label>
                <div className="mt-1 flex gap-2">
                  <div className="flex-1 relative">
                    <input
                      id="captcha"
                      name="captcha"
                      type="text"
                      required
                      value={formData.captcha}
                      onChange={handleInputChange}
                      className="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md placeholder-gray-400 focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"
                      placeholder="请输入验证码"
                      maxLength={4}
                    />
                  </div>
                  <div className="flex items-center">
                    <div 
                      className="bg-gray-100 border border-gray-300 rounded-md px-3 py-2 text-lg font-mono font-bold text-gray-800 cursor-pointer select-none"
                      onClick={handleRefreshCaptcha}
                      title="点击刷新验证码"
                    >
                      {captchaCode}
                    </div>
                  </div>
                </div>
                {errors.captcha && (
                  <p className="mt-1 text-sm text-red-600">{errors.captcha}</p>
                )}
                <p className="mt-1 text-xs text-gray-500">点击验证码图片可刷新</p>
              </div>
            )}

            {errors.general && (
              <div className="bg-red-50 border border-red-200 rounded-md p-3">
                <p className="text-sm text-red-600">{errors.general}</p>
              </div>
            )}

            <div>
              <button
                type="submit"
                disabled={isLoading}
                className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-primary hover:bg-primary-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isLoading ? '登录中...' : '登录'}
              </button>
            </div>

            {formData.userType === 'student' && (
              <div className="text-center">
                <p className="text-sm text-gray-600">
                  还没有账户？{' '}
                  <a href="/register" className="font-medium text-primary hover:text-primary-300">
                    立即注册
                  </a>
                </p>
              </div>
            )}
          </form>
        </div>
      </div>
    </div>
  );
};

export default Login; 